package com.example.chattingroom.api;

import com.example.chattingroom.model.User;
import com.example.chattingroom.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class UserAPI {
    @Resource
    UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        //1. 数据库中查询username是否存在
        //2. 如果存在，则查询password是否匹配
        //3. 如果都匹配则登陆成功，创建会话；否则登陆失败
        User user = userMapper.selectByName(username);
        if (user == null) {
            // 返回带错误信息的Map
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", "USER_NOT_FOUND"); // 新增错误类型标识
            return result;
        } else if(!user.getPassword().equals(password)) {
            // 返回带错误信息的Map
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", "WRONG_PASSWORD"); // 新增错误类型标识
            return result;
        }

        //创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        //在返回之前把 password 置空， 避免返回密码，保护隐私
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            user.setPassword("");
            System.out.println("注册 ret: " + ret);
        } catch (DuplicateKeyException e) {
            //用户名重复
            System.out.println("注册失败！用户名已存在");
            user = new User();
        }
        return user;
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        //1. 先从请求中获取会话
        HttpSession session = req.getSession(false);
        if(session == null) {
            //会话不存在，用户还没登录，返回一个空对象
            System.out.println("[getUserInfo] 当前获取不到 session 对象！");
            return new User();
        }
        //2. 从会话中获取保存的用户对象
        User user = (User) session.getAttribute("user");
        if(user == null) {
            System.out.println("[getUserInfo] 当前获取不到 user 对象！");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
